package com.example.utils;


import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;

public class AppLifecycler implements Application.ActivityLifecycleCallbacks {

    private int appCount = 0;

    private static boolean isForeground = true;

    private AppLifeCyclerCallBack callBack;

    public interface AppLifeCyclerCallBack{
        /**
         * 处于后端
         */
        void inBackground();

        /**
         * 处于前端
         */
        void inForeground();

    }

    public static boolean getAppIsForeground(){
        return isForeground;
    }

    public void register(Application application, AppLifeCyclerCallBack callBack){
        this.callBack = callBack;
        application.registerActivityLifecycleCallbacks(this);
    }

    @Override
    public void onActivityCreated(Activity activity, Bundle savedInstanceState) {

    }

    @Override
    public void onActivityStarted(Activity activity) {
        appCount++;
        if(!isForeground){
            isForeground = true;
            Log.i("test信息","当前APP进入前台");
            callBack.inForeground();
        }

    }

    @Override
    public void onActivityResumed(Activity activity) {

    }

    @Override
    public void onActivityPaused(Activity activity) {

    }

    @Override
    public void onActivityStopped(Activity activity) {
        appCount--;
        if(!validateIsInForeground()){
            // app进入后台
            isForeground = false;

            Log.i("test信息","当前APP进入后台");
            callBack.inBackground();

        }

    }

    @Override
    public void onActivitySaveInstanceState(Activity activity, Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(Activity activity) {

    }

    private boolean validateIsInForeground(){
        return appCount>0;
    }
}
